package tools.blast;

import java.io.BufferedReader;
import java.io.IOException;

public class blastM8Parser {
	BufferedReader in;
	private boolean hasMore=true;
	private blastM8Alignment hit=null;
	
	public blastM8Parser(BufferedReader in) throws IOException,Exception{
		this.in=in;
		readNext();
	}
	
	public boolean hasMore(){
		return hasMore;
	}
	
	public blastM8Alignment nextHit()throws Exception{
		if(!hasMore)
			throw new Exception("No more hits");
		blastM8Alignment tmp=hit;
		readNext();
		return tmp;
	}
	
	private void readNext() throws IOException,Exception{
		String s=in.readLine();
		if(s==null){
			hasMore=false;
		} else{
			String[] l=s.split("\t");
			if (l.length!=12)
				throw new Exception("Invalid line: "+s);
			blastM8Alignment align=new blastM8Alignment();
			align.qname=l[0];
			align.tname=l[1];
			align.identity=Double.parseDouble(l[2]);
			align.alignment_length=Integer.parseInt(l[3]);
			align.mismatches=Integer.parseInt(l[4]);
			align.gap_openings=Integer.parseInt(l[5]);
			align.qstart=Integer.parseInt(l[6]);
			align.qend=Integer.parseInt(l[7]);
			align.tstart=Integer.parseInt(l[8]);
			align.tend=Integer.parseInt(l[9]);
			align.e_value=Double.parseDouble(l[10]);
			align.score=Double.parseDouble(l[11]);
			if(align.tstart>align.tend){
				align.strand[0]='-';
				int tmp=align.tstart;
				align.tstart=align.tend;
				align.tend=tmp;
			}else
				align.strand[0]='+';

			hit=new blastM8Alignment(align);
			hasMore=true;
		}
	}
}
